package com.lswms.modules.lswms.service.impl.base;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lswms.common.page.PageData;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.common.utils.FileUtil;
import com.lswms.modules.lswms.dao.base.SkuDao;
import com.lswms.modules.lswms.dao.base.SkucategoryDao;
import com.lswms.modules.lswms.dao.stock.TradeDao;
import com.lswms.modules.lswms.dto.base.SkuDTO;
import com.lswms.modules.lswms.entity.base.SkuEntity;
import com.lswms.modules.lswms.entity.base.SkucategoryEntity;
import com.lswms.modules.lswms.entity.stock.TradeEntity;
import com.lswms.modules.lswms.excel.base.SkuExcel;
import com.lswms.modules.lswms.service.base.SkuService;
import com.lswms.modules.lswms.service.base.SkucategoryService;

/**
 * ${comments}
 *
 * @author DX sunlightcs@gmail.com
 * @since 1.0.0 2021-06-06
 */
@Service
public class SkuServiceImpl extends CrudServiceImpl<SkuDao, SkuEntity, SkuDTO> implements SkuService {

	@Autowired
	TradeDao tradeDao;

	@Autowired
	SkucategoryDao skucategoryDao;
	
	@Autowired
	SkucategoryService skucategoryService;

	@Override
	public QueryWrapper<SkuEntity> getWrapper(Map<String, Object> params) {
		String id = (String) params.get("id");
		String descr = (String) params.get("descr");
		String sku = (String) params.get("sku");
		String sort = (String) params.get("sort");
		String factorycdoe = (String) params.get("factorycdoe");
		String product = (String) params.get("product");

		String[] sorts = null;
		if (StringUtils.isNotBlank(sort)) {
			sorts = sort.split("#");
		}

		QueryWrapper<SkuEntity> wrapper = new QueryWrapper<>();
		wrapper.eq(StringUtils.isNotBlank(id), "lswms_sku.id", id);
		wrapper.eq(StringUtils.isNotBlank(sku), "lswms_sku.sku", sku);
		wrapper.in(sorts != null && sorts.length > 0, "lswms_sku.sort", sorts);
		wrapper.like(StringUtils.isNotBlank(descr), "lswms_sku.descr", descr);
		wrapper.like(StringUtils.isNotBlank(factorycdoe), "lswms_sku.factorycdoe", factorycdoe);
		wrapper.eq(StringUtils.isNotBlank(product), "lswms_sku.product", product);

		wrapper.orderByAsc("lswms_sku.descr");

		return wrapper;
	}

	@Override
	public PageData<SkuEntity> selectPageBySql(Map<String, Object> params) {
		IPage<SkuEntity> page = baseDao.selectPageBySql(getPage(params, null, false), getWrapper(params));
		return getPageData(page, SkuEntity.class);
	}

	@Override
	public SkuEntity getKey(Long id) {
		QueryWrapper<SkuEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("id", id);

		SkuEntity skuEntity = baseDao.selectOne(wrapper);
		// 获取类型的父类
		String sort = skuEntity.getSort();

		String longSort = skucategoryService.getLongSort(sort);
		
		skuEntity.setSort(longSort);
		return skuEntity;
	}

	

	@Override
	public String valideAndSave(SkuDTO dto) {
		String sku = dto.getSku();

		String sort = dto.getSort();
		String serialnumber = dto.getSerialnumber();
		String specs = dto.getSpecs();
		// sort在前台会以父类#子类的格式传给后台，后台处理数据，只取最后的不会空的子类

		if (StringUtils.isNotBlank(sort)) {
			String[] sortArray = sort.split("#");
			sort = sortArray[sortArray.length - 1];
			dto.setSort(sort);
		}

		// 录入的sku为空时，sort、specs和serialnumber拼接成sku
		if (StringUtils.isBlank(sku)) {
			sku = StringUtils.EMPTY;
			if (StringUtils.isNotBlank(sort)) {
				sku += sort;
			}
			if (StringUtils.isNotBlank(specs)) {
				sku += specs;
			}
			if (StringUtils.isNotBlank(serialnumber)) {
				sku += serialnumber;
			}
		}

		if (StringUtils.isBlank(sku)) {
			return "请录入物料编码";
		}

		// 校验sku是否已存在
		QueryWrapper<SkuEntity> skuQuery = new QueryWrapper<SkuEntity>();
		skuQuery.eq("sku", sku);

		Integer count = baseDao.selectCount(skuQuery);
		if (count > 0) {
			return "物料编码：" + sku + "已存在，请重新录入";
		}

		String msg = valide(dto);
		if (StringUtils.isNotBlank(msg)) {
			return msg;
		}

		SkuEntity skuEntity = new SkuEntity();
		skuEntity.setSku(sku);
		skuEntity.setDescr(StringUtils.trimToEmpty(dto.getDescr()));
		skuEntity.setPack(StringUtils.trimToEmpty(dto.getPack()));
		skuEntity.setSort(StringUtils.trimToEmpty(dto.getSort()));
		skuEntity.setUnit(StringUtils.trimToEmpty(dto.getUnit()));
		skuEntity.setWeight(dto.getWeight());
		skuEntity.setLength(dto.getLength());
		skuEntity.setHeight(dto.getHeight());
		skuEntity.setWidth(dto.getWidth());
		skuEntity.setLotrule(StringUtils.trimToEmpty(dto.getLotrule()));
		skuEntity.setIsuniquecode(StringUtils.trimToEmpty(dto.getIsuniquecode()));
		skuEntity.setStatus(StringUtils.trimToEmpty(dto.getStatus()));
		skuEntity.setReserve1(StringUtils.trimToEmpty(dto.getReserve1()));
		skuEntity.setReserve2(StringUtils.trimToEmpty(dto.getReserve2()));
		skuEntity.setReserve3(StringUtils.trimToEmpty(dto.getReserve3()));
		skuEntity.setReserve4(StringUtils.trimToEmpty(dto.getReserve4()));
		skuEntity.setReserve5(StringUtils.trimToEmpty(dto.getReserve5()));
		skuEntity.setStrategykey(StringUtils.trimToEmpty(dto.getStrategykey()));
		skuEntity.setZonecode(StringUtils.trimToEmpty(dto.getZonecode()));
		skuEntity.setAllocationstrategy(StringUtils.trimToEmpty(dto.getAllocationstrategy()));
		skuEntity.setRolateby(StringUtils.trimToEmpty(dto.getRolateby()));
		skuEntity.setSpecs(StringUtils.trimToEmpty(dto.getSpecs()));
		skuEntity.setIsconsumable(StringUtils.trimToEmpty(dto.getIsconsumable()));
		skuEntity.setPrice(dto.getPrice());
		skuEntity.setFactory(StringUtils.trimToEmpty(dto.getFactory()));
		skuEntity.setFactorycdoe(StringUtils.trimToEmpty(dto.getFactorycdoe()));
		skuEntity.setProduct(StringUtils.trimToEmpty(dto.getProduct()));
		skuEntity.setName(StringUtils.trimToEmpty(dto.getName()));
		skuEntity.setSafetyqty(dto.getSafetyqty());
		skuEntity.setAccuracyclass(StringUtils.trimToEmpty(dto.getAccuracyclass()));
		skuEntity.setEffectlife(dto.getEffectlife());
		skuEntity.setWarningdays(dto.getWarningdays());

		baseDao.insert(skuEntity);

		return null;
	}

	@Override
	public String valideAndUpdate(SkuDTO dto) {

		String sort = dto.getSort();
		if (StringUtils.isNotBlank(sort)) {
			String[] sortArray = sort.split("#");
			sort = sortArray[sortArray.length - 1];
			dto.setSort(sort);
		}

		String msg = valide(dto);
		if (StringUtils.isNotBlank(msg)) {
			return msg;
		}

		SkuEntity skuEntity = new SkuEntity();
		skuEntity.setDescr(StringUtils.trimToEmpty(dto.getDescr()));
		skuEntity.setPack(StringUtils.trimToEmpty(dto.getPack()));
		skuEntity.setSort(StringUtils.trimToEmpty(dto.getSort()));
		skuEntity.setUnit(StringUtils.trimToEmpty(dto.getUnit()));
		skuEntity.setWeight(dto.getWeight());
		skuEntity.setLength(dto.getLength());
		skuEntity.setHeight(dto.getHeight());
		skuEntity.setWidth(dto.getWidth());
		skuEntity.setLotrule(StringUtils.trimToEmpty(dto.getLotrule()));
		skuEntity.setIsuniquecode(StringUtils.trimToEmpty(dto.getIsuniquecode()));
		skuEntity.setStatus(StringUtils.trimToEmpty(dto.getStatus()));
		skuEntity.setReserve1(StringUtils.trimToEmpty(dto.getReserve1()));
		skuEntity.setReserve2(StringUtils.trimToEmpty(dto.getReserve2()));
		skuEntity.setReserve3(StringUtils.trimToEmpty(dto.getReserve3()));
		skuEntity.setReserve4(StringUtils.trimToEmpty(dto.getReserve4()));
		skuEntity.setReserve5(StringUtils.trimToEmpty(dto.getReserve5()));
		skuEntity.setStrategykey(StringUtils.trimToEmpty(dto.getStrategykey()));
		skuEntity.setZonecode(StringUtils.trimToEmpty(dto.getZonecode()));
		skuEntity.setAllocationstrategy(StringUtils.trimToEmpty(dto.getAllocationstrategy()));
		skuEntity.setRolateby(StringUtils.trimToEmpty(dto.getRolateby()));
		skuEntity.setSpecs(StringUtils.trimToEmpty(dto.getSpecs()));
		skuEntity.setIsconsumable(StringUtils.trimToEmpty(dto.getIsconsumable()));
		skuEntity.setPrice(dto.getPrice());
		skuEntity.setFactory(StringUtils.trimToEmpty(dto.getFactory()));
		skuEntity.setFactorycdoe(StringUtils.trimToEmpty(dto.getFactorycdoe()));
		skuEntity.setProduct(StringUtils.trimToEmpty(dto.getProduct()));
		skuEntity.setName(StringUtils.trimToEmpty(dto.getName()));
		skuEntity.setSafetyqty(dto.getSafetyqty());
		skuEntity.setAccuracyclass(StringUtils.trimToEmpty(dto.getAccuracyclass()));
		skuEntity.setEffectlife(dto.getEffectlife());
		skuEntity.setWarningdays(dto.getWarningdays());

		UpdateWrapper<SkuEntity> update = new UpdateWrapper<SkuEntity>();
		update.eq("sku", dto.getSku());
		baseDao.update(skuEntity, update);
		return null;

	}

	private String valide(SkuDTO dto) {

		Integer weight = dto.getWeight();
		Integer length = dto.getLength();
		Integer width = dto.getWidth();
		Integer height = dto.getHeight();
		BigDecimal price = dto.getPrice();
		BigDecimal safetyqty = dto.getSafetyqty();
		BigDecimal effectlife = dto.getEffectlife();
		BigDecimal warningdays = dto.getWarningdays();

		// 校验价格
		if (price == null) {
			price = BigDecimal.ZERO;
			dto.setPrice(price);
		}
		if (price.compareTo(BigDecimal.ZERO) < 0) {
			return "价格不能为负数，请重新录入";
		}
		// 校验安全库存
		if (safetyqty == null) {
			safetyqty = BigDecimal.ZERO;
			dto.setSafetyqty(safetyqty);
		}
		if (safetyqty.compareTo(BigDecimal.ZERO) < 0) {
			return "安全不能为负数，请重新录入";
		}
		// 有效期天数
		if (effectlife == null) {
			effectlife = BigDecimal.ZERO;
			dto.setEffectlife(effectlife);
		}
		if (effectlife.compareTo(BigDecimal.ZERO) < 0) {
			return "有效期天数不能为负数，请重新录入";
		}

		// 提前预警天数
		if (warningdays == null) {
			warningdays = BigDecimal.ZERO;
			dto.setWarningdays(warningdays);
		}
		if (warningdays.compareTo(BigDecimal.ZERO) < 0) {
			return "提前预警天数不能为负数，请重新录入";
		}

		// 提前预警天数
		if (weight == null) {
			weight = 0;
			dto.setWeight(weight);
		}
		if (weight < 0) {
			return "重量不能为负数，请重新录入";
		}

		// 提前预警天数
		if (length == null) {
			length = 0;
			dto.setLength(length);
		}
		if (length < 0) {
			return "长度不能为负数，请重新录入";
		}

		// 提前预警天数
		if (width == null) {
			width = 0;
			dto.setWidth(width);
		}
		if (width < 0) {
			return "宽度不能为负数，请重新录入";
		}

		// 提前预警天数
		if (height == null) {
			height = 0;
			dto.setHeight(height);
		}
		if (height < 0) {
			return "高度不能为负数，请重新录入";
		}
		return null;
	}

	@Override
	public String deleteByKey(String[] skus) {
		QueryWrapper<TradeEntity> query = new QueryWrapper<TradeEntity>();
		query.in("sku", skus);
		Integer count = tradeDao.selectCount(query);
		if (count > 0) {
			return "选择的物料已参与业务，无法删除";
		}

		UpdateWrapper<SkuEntity> skuUpdate = new UpdateWrapper<SkuEntity>();
		skuUpdate.in("sku", skus);
		baseDao.delete(skuUpdate);

		return null;
	}

	@Override
	public PageData<SkuEntity> getStock(Map<String, Object> params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public SkuEntity getSkuByCode(String sku) {
		QueryWrapper<SkuEntity> query = new QueryWrapper<SkuEntity>();
		query.eq("sku", sku);
		query.or().eq("factorycdoe", sku);

		List<SkuEntity> list = baseDao.selectList(query);
		if (list.size() > 0) {
			return list.get(0);
		}

		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String importExcel(MultipartFile file) {
		List<SkuExcel> skuEntities;
		try {
			skuEntities = FileUtil.importExcel(file, 0, 1, SkuExcel.class);
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return e.getMessage();
		}

		List<String> skuList = baseDao.getSkuList();

		Set<String> skuSet = new HashSet<String>();

		for (SkuExcel item : skuEntities) {
			String sku = item.getSku();
			sku = StringUtils.trim(sku);
			if (skuSet.contains(sku)) {
				return "导入文件中的物料编码重复:" + sku;
			} else {
				skuSet.add(sku);
			}

			for (String one : skuList) {
				if (StringUtils.trimToEmpty(item.getSku()).equals(one)) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return "该编码已占用:" + item.getSku();
				}
			}

		}

		List<SkucategoryEntity> skuCList = skucategoryDao.selectList(null);
		for (SkuExcel item : skuEntities) {
			boolean skucateExists = false;
			for (SkucategoryEntity skucategoryEntity : skuCList) {
				if (StringUtils.trimToEmpty(item.getSort()).equals(skucategoryEntity.getCategorykey())) {
					skucateExists = true;
					continue;
				}
			}
			if (!skucateExists) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return "分类:" + item.getSort() + "不存在,请先添加";
			}
		}

		for (SkuExcel item : skuEntities) {
			SkuEntity skuEntity = new SkuEntity();

			skuEntity.setSku(StringUtils.trimToEmpty(item.getSku()));
			skuEntity.setDescr(StringUtils.trimToEmpty(item.getDescr()));
			skuEntity.setSort(StringUtils.trimToEmpty(item.getSort()));
			skuEntity.setUnit(StringUtils.trimToEmpty(item.getUnit()));
			skuEntity.setSpecs(StringUtils.trimToEmpty(item.getSpecs()));

			String isuniquecode = StringUtils.trimToEmpty(item.getIsuniquecode());
			if (isuniquecode.equals("1") || isuniquecode.equals("是")) {
				isuniquecode = "1";
			} else {
				isuniquecode = "0";
			}
			skuEntity.setIsuniquecode(isuniquecode);

			String isconsumable = StringUtils.trimToEmpty(item.getIsconsumable());
			if (isconsumable.equals("1") || isconsumable.equals("是")) {
				isconsumable = "1";
			} else {
				isconsumable = "0";
			}
			skuEntity.setIsconsumable(isconsumable);
			skuEntity.setPrice(item.getPrice());
			skuEntity.setFactory(item.getFactory());
			skuEntity.setFactorycdoe(item.getFactorycdoe());
			skuEntity.setName(item.getName());
			skuEntity.setAccuracyclass(item.getAccuracyclass());
			skuEntity.setSafetyqty(item.getSafetyqty());
			skuEntity.setEffectlife(item.getEffectlife());
			skuEntity.setWarningdays(item.getWarningdays());
			skuEntity.setProduct(item.getProduct());
			skuEntity.setAllocationstrategy("N01");
			skuEntity.setRolateby("lot1");
			skuEntity.setStrategykey("0000000002");

			baseDao.insert(skuEntity);
		}

		return null;
	}

}
